<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示标签 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      ></el-alert>
      <!-- 级联选择器 -->
      <div class="mt15">
        选择商品分类：<el-cascader
          v-model="selectedValue"
          :options="cateList"
          :props="cascaderProps"
          @change="handleChange"
          clearable
        ></el-cascader>
        <!-- tabs标签 -->
        <el-tabs v-model="activeName" @tab-click="tabHandleClick">
          <!-- 动态参数 -->
          <el-tab-pane label="动态参数" name="many">
            <el-button
              size="mini"
              type="primary"
              :disabled="selectedValue.length !== 3"
              @click="dialogVisible = true"
              >添加参数</el-button
            >
            <el-table :data="manyTableData" border>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(val, index) in scope.row.attr_vals"
                    :key="val"
                    closable
                    @close="handleClose(scope.row, index)"
                  >
                    {{ val }}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column
                prop="attr_name"
                label="参数名称"
              ></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="text" @click="edit(scope.row)"
                    >编辑</el-button
                  >
                  <el-button type="text" @click="del(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 静态属性 -->
          <el-tab-pane label="静态属性" name="only">
            <el-button
              size="mini"
              type="primary"
              :disabled="selectedValue.length !== 3"
              @click="dialogVisible = true"
              >添加属性</el-button
            >
            <el-table :data="onlyTableData" border>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(val, index) in scope.row.attr_vals"
                    :key="val"
                    closable
                    @close="handleClose(scope.row, index)"
                  >
                    {{ val }}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column
                prop="attr_name"
                label="参数名称"
              ></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="text" @click="edit(scope.row)"
                    >编辑</el-button
                  >
                  <el-button type="text" @click="del(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      @close="clearForm"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-form-item :label="dialogLable" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedValue: [],
      cateList: [],
      cascaderProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      activeName: "many",
      manyTableData: [],
      onlyTableData: [],
      dialogVisible: false,
      addForm: {
        attr_name: "",
      },
      addFormRules: {
        attr_name: [
          { required: true, message: "请填写参数名称", trigger: "blur" },
        ],
      },
      isEdit: false,
      cat_id: null,
      attr_id: null,
    };
  },
  methods: {
    async getCate() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 3 },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取失败");
      }
      this.cateList = res.data;
    },
    handleChange() {
      if (this.selectedValue.length !== 3) {
        this.selectedValue = [];
        this.onlyTableData = [];
        this.manyTableData = [];
        return;
      }
      this.getParamsData();
    },
    tabHandleClick() {
      this.getParamsData();
    },
    async getParamsData() {
      if (this.selectedValue.length !== 3) {
        this.selectedValue = [];
        return;
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取失败");
      }
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },
    clearForm() {
      this.addForm.attr_name = "";
      this.isEdit = false;
      this.cat_id = null;
      this.attr_id = null;
      this.$refs.addFormRef.resetFields();
    },
    sureBtn() {
      this.$refs.addFormRef.validate(async (value) => {
        if (!value) return;
        // 非编辑按钮时
        if (!this.isEdit) {
          const { data: res } = await this.$http.post(
            `categories/${this.selectedValue[2]}/attributes`,
            {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName,
            }
          );
          if (res.meta.status !== 201) {
            return this.$message.error("创建失败");
          }
          this.$message.success("创建成功");
        } else {
          const { data: res } = await this.$http.put(
            `categories/${this.cat_id}/attributes/${this.attr_id}`,
            {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName,
            }
          );
          if (res.meta.status !== 200) {
            return this.$message.error("更新失败");
          }
          this.$message.success("更新成功");
        }
        this.getParamsData();
        this.dialogVisible = false;
        this.clearForm();
      });
    },
    edit(msg) {
      this.isEdit = true;
      this.addForm.attr_name = msg.attr_name;
      this.cat_id = msg.cat_id;
      this.attr_id = msg.attr_id;
      this.dialogVisible = true;
    },
    del(message) {
      this.$confirm("确定删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${message.cat_id}/attributes/${message.attr_id}`
          );
          if (res.meta.status !== 200) {
            return this.$message.error("删除失败");
          }
          this.$message.success("删除成功");
          this.getParamsData();
        })
        .catch(() => {});
    },
    showInput(e) {
      e.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async handleInputConfirm(e) {
      let inputValue = e.inputValue;
      if (inputValue) {
        e.attr_vals.push(inputValue);
        this.editParams(e);
      }
      e.inputVisible = false;
      e.inputValue = "";
    },
    handleClose(e, index) {
      e.attr_vals.splice(index, 1);
      this.editParams(e);
    },
    // 操作参数
    async editParams(e) {
      const { data: res } = await this.$http.put(
        `categories/${e.cat_id}/attributes/${e.attr_id}`,
        {
          attr_sel: e.attr_sel,
          attr_name: e.attr_name,
          attr_vals: e.attr_vals.join(","),
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("更新失败");
      }
      this.$message.success("更新成功");
    },
  },
  computed: {
    cateId() {
      if (this.selectedValue.length === 3) {
        return this.selectedValue[2];
      }
      return null;
    },
    dialogTitle() {
      if (this.activeName === "many" && !this.isEdit) {
        return "添加参数";
      } else if (this.activeName === "only" && !this.isEdit) {
        return "添加属性";
      } else if (this.activeName === "many" && this.isEdit) {
        return "编辑参数";
      } else {
        return "编辑属性";
      }
    },
    dialogLable() {
      if (this.activeName === "many") {
        return "参数";
      } else {
        return "属性";
      }
    },
  },
  created() {
    this.getCate();
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin-right: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>